package com.lagou.minicat.connector;

import com.lagou.minicat.container.Host;
import com.lagou.minicat.service.Service;
import com.lagou.minicat.servlet.Request;
import com.lagou.minicat.servlet.Response;
import com.lagou.minicat.servlet.Servlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

/**
 * @ClassName AccpectHandle
 * @Description
 * @Author playboy
 * @Date 2021/5/22 5:38 下午
 * @Version 1.0
 **/
public class AccpectHandle implements Runnable {
	private static Logger log = LoggerFactory.getLogger(AccpectHandle.class);

	private Socket socket;

	private Service service;

	public AccpectHandle(Socket socket, Service service) {
		this.socket = socket;
		this.service = service;
	}

	@Override
	public void run() {
		try {
			Request request = new Request(socket.getInputStream());
			Response response = new Response(socket.getOutputStream());
			//根据请求的host和url，查找到对应的host，context，wrapper，并且封装到Mappingdata，放到request中
			service.getMapper().map(request);
			if (request.isDynamic()) {
				//直接从mappingdata中获取到Wrapper，然后获取到要调用的servlet
				Servlet servlet = request.getServlet();
				//调用对应的servlet
				servlet.service(request, response);
			} else {
				//静态资源
				//直接加载，如果找不到就报404
				if (request.getMappingData().getHost() != null) {
					Host host = request.getMappingData().getHost();
					String appBase = host.getAppBase();
					File source = new File(appBase + request.getUrl());
					response.outHtml(source.getAbsolutePath());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				//不要忘了关闭连接
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
